package org.orz.cloud.lock.zookeeper;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.orz.cloud.lock.Lock;
import org.orz.cloud.lock.LockFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Zk分布式锁工厂类，实现了{@link LockFactory}接口，用来初始化分布式锁，
 * 以及创建分布式锁工作。
 */
public class ZkLockFactory implements LockFactory<ZkProperties> {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(ZkLockFactory.class);
	
	private CuratorFramework curator = null;

	@Override
	public void init(ZkProperties properties) {
		LOGGER.info("Start init zk lock,url: "+properties.getServers());
		if(curator==null){
			curator = CuratorFrameworkFactory.builder()
					.sessionTimeoutMs(30000)
					.connectionTimeoutMs(30000)
					.retryPolicy(new ExponentialBackoffRetry(1000, Integer.MAX_VALUE)).connectString(properties.getServers()).build();
			curator.getConnectionStateListenable().addListener(new ZkListener()) ;
			curator.start();
			ZkLock.setCurator(curator);
		}
		LOGGER.info("End init zk lock");
	}
	
	@Override
	public Lock createLock() {
		return new ZkLock();
	}

}
